package openweather

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

type WeatherService struct {
	AppID string
	Units string
	Lang  string
}

func NewWeatherService(AppID string, units string, lang string) *WeatherService {
	return &WeatherService{
		AppID: AppID,
		Units: units,
		Lang:  lang,
	}

}

func (w *WeatherService) GetWeatherByCityName(cityName string) (*WeatherResponse, error) {
	resp, err := http.Get(fmt.Sprintf("https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=%s&lang=%s", cityName, w.AppID, w.Units, w.Lang))
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	defer resp.Body.Close()
	wr := &WeatherResponse{}
	bytesResp, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(bytesResp, wr)
	if err != nil {
		return nil, err
	}

	return wr, nil
}
